var text
//网站
querybrandWebsites()
function querybrandWebsites() {
    $.ajax({
        type: "POST",
        url: root.brandWebsite.query,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({

        }),
        success: function (data) {
            for (var i=0;i<data.data.data.length;i++){
                $("#websiteId").append("<option value=" + data.data.data[i].id + " >" + data.data.data[i].websiteName + "</option>")
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//一级分类展示
classa()
function classa() {
    $("#classSet2").html("")
    $.ajax({
        type: "POST",
        url: root.brandWebsite.searchCategory,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId": $("#websiteId").val(),
            "categoryId":"",
        }),
        success: function (data) {
            var levelOnedata=data.data.categoryList
            var levelOne=""
            for (var i=0;i<levelOnedata.length;i++){
                levelOne += '<li class="clearfix pl-10 mb-5">' +
                    '                           <div class="f-l pd-5" style="margin-left: 49px;">' +
                    '                                    <input  name="classification01" type="radio" data-name="'+levelOnedata[i].categoryName+'" value="'+levelOnedata[i].id+'" class="radio" onclick="classb('+levelOnedata[i].id+')">' +
                    '                                    <label class="pl-10"> <input title="" type="text" value="'+levelOnedata[i].categoryName+'" disabled="" style="height: 24px;width: 145px;border: 0px;background: white;margin-top: -4px">' +
                    '                                    </label></div>' +
                    '                    </li>'

            }
            $("#classSet1").html(levelOne)


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//二级展示
function classb(val){
    $.ajax({
        type: "POST",
        url: root.brandWebsite.searchCategory,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId": $("#websiteId").val(),
            "categoryId":val,
        }),
        success: function (data) {
            var levelOnedata=data.data.sedCategoryList
            var levelOne=""
            for (var i=0;i<levelOnedata.length;i++){
                levelOne += '<li class="clearfix pl-10 mb-5">' +
                    '                           <div class="f-l pd-5" style="margin-left: 49px;">' +
                    '                                    <input  name="aaaa" type="radio" data-name="'+levelOnedata[i].categoryName+'" value="'+levelOnedata[i].id+'" class="rad">' +
                    '                                    <label class="pl-10"> <input title="" type="text" value="'+levelOnedata[i].categoryName+'" disabled="" style="height: 24px;width: 145px;border: 0px;background: white;margin-top: -4px">' +
                    '                                    </label></div>' +
                    '                    </li>'

            }
            $("#classSet2").html(levelOne)


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
if(sessionStorage.getItem("productManagementID")!='新建'){
    $.ajax({
        type: "post",
        url: root.brandWebsite.saerchProdectDetail,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: {
            "id":sessionStorage.getItem("productManagementID"),
            "websiteId":$("#websiteId").val(),
        },
        success: function (data) {
            $("#websiteId").val(data.data.product.websiteId)
            classa()
            $("#productName").val(data.data.product.productName)
            $("#myImsg").attr("src",data.data.product.productPictureUrl)
            var inputval= $("#classSet1 li").find('input:radio')
            for (var l=0;l<inputval.length;l++) {
                if(data.data.product.categoryId==$(inputval)[l].value){
                    $(inputval)[l].checked=true
                    classb(data.data.product.categoryId)
                }
            }
            var inputval2= $("#classSet2 li").find('input:radio')
            for (var d=0;d<inputval2.length;d++) {
                if(data.data.product.sedCategoryId==$(inputval2)[d].value){
                    $(inputval2)[d].checked=true
                }
            }

            ue.ready(function() {
                ue.setContent(data.data.product.introductionMsg);
            });
            for (var h=1;h<6;h++) {
                $.each(data.data.buyUrl,function(k,v) {
                    if($("#buyUrl"+h).attr("data-id")==v.channelId){
                        $("#buyUrl" + h).val(v.buyUrl)
                        $("#myImg" + h).attr("src",v.picUrl)
                    }

                })
            }
            $("#pageTitle").val(data.data.tdk.pageTitle)
            $("#pageDescription").val(data.data.tdk.pageDescription)
            $("#pageKeywords").val(data.data.tdk.pageKeywords)
            $("#TDKid").val(data.data.tdk.id)

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}


function addBtn(cen) {
    $(cen).prev().trigger('click');
}
//图片上传验证
var formData = new FormData();
// 提交上传图片
function getupfilerul(can,e){
    var formData = new FormData();
    formData.append('file',$(can)[0].files[0]);
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            for(var i=0; i<data.length; i++){
                $(can).parent().parent().parent().find('img').attr("src", data[0].fullPath);
                $(can).parent().find('.fileupone').html('更换图片')
                $("#fileUpone").attr('type','text');
                $("#fileUpone").attr('type','file');
            }

        }
    })
}
// 上传图片返现
function putDataToPage(e,can,type) {
    //验证
     verificationPicFileType(can)
     verificationPicFileSize(can)
    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;
                console.log(height)
                if(type==1){
                    if (Number(width) == Number(182) && Number(height) == Number(182)){
                        getupfilerul(can,e)

                    }else {
                        $.Huimodalalert('请上传正确格式图片 ',2000);
                        file.value = "";
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        return;

                    }
                }else {
                    if (Number(width) == Number(68) && Number(height) == Number(55)){
                        getupfilerul(can,e)

                    }else {
                        $.Huimodalalert('请上传正确格式图片 ',2000);
                        file.value = "";
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        return;

                    }
                }

                getupfilerul(can,e)

            };


        }
    }
    formData.append('file', $(can)[0].files[0]);
}
// 图片类型验证
function verificationPicFileType(file) {
    var flag=false;
    var fileTypes = [".jpg", ".png",".jpeg"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('请上传正确格式图片',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}
//图片大小验证
function verificationPicFileSize(file) {
    var flag=false;
    var fileSize = 0;
    var fileMaxSize = Number(1024);
    var filePath = file.value;
    if(filePath){
        fileSize =file.files[0].size;
        var size = fileSize / Number(1024);
        if (size > fileMaxSize) {
            $.Huimodalalert('上传图片过大，请压缩大小后再试',2000);
            file.value = "";
            flag=false;
        }else{
            flag=true;
        }
    }
    return flag;
}
//删除图片
function deletfilefns(e){
    edit_or_not=false
    $('#fileupones').html('图片上传')
    $(e).parent().parent().parent().find('img').attr('src','')
    $("#fileUpone").attr('type','text');
    $("#fileUpone").attr('type','file');

}

function commoditydetailadd() {
    var buyUrlsdata={}
    var buyUrlsarr=[]

    ue.ready(function() {
        text = ue.getContent();
    });
    console.log($("#classSet1 li").find('input:radio:checked').val())
    if($("#productName").val()==""||$("#myImsg").attr("src")==""||$("#classSet1 li").find('input:radio:checked').val()==undefined ){
        $.Huimodalalert('请完善必填信息',2000);
        return false;
    }else {
        if($("#classSet1 li").find('input:radio:checked').val()!=undefined){
            if($("#classSet2 li").find('input:radio:checked').val()==undefined||$("#classSet2 li").length<0){
                $.Huimodalalert('请完善产品分类',2000);
                return false;
            }else {
                if(text==""||$("#pageTitle").val()=="" ||$("#pageDescription").val()==""||$("#pageKeywords").val()=="" ){
                    $.Huimodalalert('请完善必填信息',2000);
                    return false;
                }
            }
        }
    }
    for (var h=1;h<6;h++) {
        buyUrlsdata={
            "channelId":$("#buyUrl"+h).attr("data-id"),
            "buyUrl":$("#buyUrl"+h).val(),
            "picUrl":$("#myImg"+h).attr("src")
        }
        if($("#buyUrl"+h).val()==""&&$("#myImg"+h).attr("src")!=""){
            $.Huimodalalert('请完善购买渠道链接',2000);

            return false;
        }
        if($("#buyUrl"+h).val()!="" && $("#myImg"+h).attr("src")==""){
            $.Huimodalalert('请完善购买渠道配图',2000);
            return false;
        }
        if($("#buyUrl"+h).val()!=""){
            if($("#buyUrl"+h).val().indexOf("https://")==-1){
                $.Huimodalalert('请填写正确连接',2000);
                return false;
            }
        }

        if($("#buyUrl"+h).val()!=""&&$("#myImg"+h).attr("src")!=""){
            buyUrlsarr.push(buyUrlsdata)
        }

    }

    var productall={}
    var productarr=[]
    var tdkdataall={}
    var tdkdataarr=[]
    if(sessionStorage.getItem("productManagementID")=="新建"){
        productall={
            "websiteId":$("#websiteId").val(),
            "productName":$("#productName").val(),
            "productPictureUrl":$("#myImsg").attr("src"),
            "categoryId":$("#classSet1 li").find('input:radio:checked').val(),
            "sedCategoryId":$("#classSet2 li").find('input:radio:checked').val(),
            "isRecommend":"1",
            "isPageShow":"1",
            "introductionMsg":text,
            "buyUrls":JSON.stringify(buyUrlsarr),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }

        tdkdataall={
            "websiteId":$("#websiteId").val(),
            "pageType":5,
            "pageTitle":$("#pageTitle").val(),
            "pageDescription":$("#pageDescription").val(),
            "pageKeywords":$("#pageKeywords").val(),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }

        $.ajax({
            type: "POST",
            url: root.brandWebsite.addProduct,
            cache: false,  //禁用缓存
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "product":productall,
                "tdk":tdkdataall,
            }),
            success: function (data) {
                if(data.errorCode==0){
                        layer.msg("保存成功",{icon: 6,time:2000},function () {
                            setTimeout(function () {
                                window.parent.querybrandWebsitess();
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            })
                        });
                }else {
                    $.Huimodalalert(data.msg,2000);
                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }else {
        productall={
            "websiteId":$("#websiteId").val(),
            "id":sessionStorage.getItem("productManagementID"),
            "productName":$("#productName").val(),
            "productPictureUrl":$("#myImsg").attr("src"),
            "categoryId":$("#classSet1 li").find('input:radio:checked').val(),
            "sedCategoryId":$("#classSet2 li").find('input:radio:checked').val(),
            "categoryName":$("#classSet1 li").find('input:radio:checked').attr("data-name"),
            "sedCategoryName":$("#classSet2 li").find('input:radio:checked').attr("data-name"),
            "introductionMsg":text,
            "buyUrls":JSON.stringify(buyUrlsarr),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }

        tdkdataall={
            "id":$("#TDKid").val(),
            "msgId":sessionStorage.getItem("productManagementID"),
            "pageType":5,
            "pageTitle":$("#pageTitle").val(),
            "pageDescription":$("#pageDescription").val(),
            "pageKeywords":$("#pageKeywords").val(),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }

        $.ajax({
            type: "POST",
            url: root.brandWebsite.updateProductDetail,
            cache: false,  //禁用缓存
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({
                "product":productall,
                "tdk":tdkdataall,
            }),
            success: function (data) {
                if(data.errorCode==0){
                        layer.msg("保存成功",{icon: 6,time:2000},function () {
                            setTimeout(function () {
                                window.parent.querybrandWebsitess();
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            })
                        });
                }else {
                    $.Huimodalalert(data.msg,2000);
                }
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
    }

    
}